<template>
  <el-dialog :model-value="dialogVisible" title="用户列表" width="65%" align-center @closed="handleClose">
    <el-button-group>
      <el-button type="primary" :icon="CirclePlus" v-auth="'AddUser'" @click="handleOpenDialogUser">
        添加用户
      </el-button>
      <el-button type="danger" :icon="Remove" v-auth="'RemoveUser'" @click="handleRemoveUsers">移除用户</el-button>
    </el-button-group>
    <x-table
      ref="refTable"
      name="用户"
      :height="tableHeight"
      :columns="columns"
      :init-sort="{ userName: 'ascending' }"
      :data="tableData.resp.list"
      :total="tableData.resp.total"
      :loading="tableData.loading"
      :init-query="false"
      @query="handleQuery"
    >
      <template #column-userStatus="scope">
        <el-tag v-if="scope.data === 0" type="info">禁用</el-tag>
        <template v-else>启用</template>
      </template>
    </x-table>
    <DialogUser
      ref="refDialogUser"
      v-model:visible="dialogUserVisible"
      :api="dialogUserApi"
      @ok="handleSelectedUsers"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, nextTick } from 'vue'
import { ElDialog, ElMessage, ElTag } from 'element-plus'
import { CirclePlus, Remove } from '@element-plus/icons-vue'
import { roleApi } from '@/api/modules/system/role'
import type { Role } from '@/api/modules/system/role'
import type { User } from '@/api/modules/system/user'
import { useUser } from '@/views/system/user/hook'
import { util, confirm } from '@/utils'
import DialogUser from '@/views/system/user/DialogList.vue'

const props = withDefaults(defineProps<{ visible: boolean }>(), {
  visible: false
})
const emits = defineEmits(['update', 'update:visible'])

const dialogVisible = computed(() => props.visible)
const tableHeight = computed(() => util.getAppHeight() * 0.55)

const currentRoleId = ref('')
const setRole = (role: Role) => {
  currentRoleId.value = role.roleId
  nextTick(() => {
    refTable.value.refresh()
  })
}

const userApi = (page: AxiosType.Pagination) => {
  return roleApi.findUserPage(page, currentRoleId.value)
}
const { refTable, tableData, handleQuery, columns } = useUser(userApi)

// 添加用户
const refDialogUser = ref()
const dialogUserVisible = ref(false)
const handleOpenDialogUser = () => {
  dialogUserVisible.value = true
  refDialogUser.value.refresh()
}
const dialogUserApi = (page: AxiosType.Pagination) => {
  return roleApi.findUserPage(page, currentRoleId.value, { exclude: true })
}
const handleSelectedUsers = ({ users }: any) => {
  // log.action('添加角色用户')
  const userIds = users.map((user: User) => {
    return user.userId
  })
  roleApi.addUsers(currentRoleId.value, userIds).then(resp => {
    if (resp.success) {
      refTable.value.refresh()
      emits('update')
      ElMessage.success(`${userIds.length} 个用户被添加`)
    } else {
      ElMessage.error(resp.message)
    }
  })
}

// 移除用户
const handleRemoveUsers = () => {
  if (refTable.value.selection.length === 0) {
    ElMessage.warning({ message: '请至少勾选列表中的一条数据' })
    return
  }
  confirm('确定要移除用户吗?', () => {
    // log.action('移除角色用户')
    const userIds = refTable.value.selection.map((item: User) => {
      return item.userId
    })
    roleApi.removeUsers(currentRoleId.value, userIds).then(resp => {
      if (resp.success) {
        refTable.value.refresh()
        emits('update')
        ElMessage.success(`${userIds.length} 个用户被移除`)
      } else {
        ElMessage.error(resp.message)
      }
    })
  })
}

const handleClose = () => {
  emits('update:visible', false)
}

defineExpose({ setRole })
</script>

<style lang="scss" scoped></style>
